package com.yc.zookeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;

public class Demo1 {
	
	/**
	 * 建立连接
	 * @return
	 * @throws IOException 
	 */
	private ZooKeeper getConnect() throws Exception {
		CountDownLatch cdl = new CountDownLatch(1);
		
		ZooKeeper zookeeper = new ZooKeeper("172.16.67.127:2181,172.16.67.128:2181,172.16.67.122:2181", 5000, new Watcher() {
			
			@Override
			public void process(WatchedEvent event) {
				System.out.println("事件：节点" + event.getPath() + " - 类型：" + event.getType());
				if (KeeperState.SyncConnected == event.getState()) {//连接成功
					if (EventType.None == event.getType() && null == event.getPath()) {
						System.out.println("连接成功");
						cdl.countDown();
					}
				}
				
			}
		});
		//zookeeper异步处理。使用线程门栓同步等待 直到连接成功,再返回
		cdl.await();
		return zookeeper;
	}
	
	/**
	 * 创建临时节点
	 * @param path
	 * @throws Exception 
	 */
	public void m1(String path) throws Exception {
		ZooKeeper zk = getConnect();
		try {
			zk.create(path, "abcd".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
		} catch (NodeExistsException e) {
			System.out.println("节点已经存在，创建失败！");
			return;
		}
		
		System.out.println("创建临时节点[" + path + "]完成");
		Thread.sleep(Integer.MAX_VALUE);
	}
	
	/**
	 * 创建永久节点
	 * @param path
	 * @throws Exception
	 */
	public void m2(String path) throws Exception {
		ZooKeeper zk = getConnect();
		zk.create(path, "abcd".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		System.out.println("创建永久节点[" + path + "]完成");
		Thread.sleep(Integer.MAX_VALUE);
	}

	public static void main(String[] args) throws Exception {
		Demo1 d = new Demo1();
		d.m1("/yc/m1");
//		d.m2("/yc/m2");

	}

}
